<script setup>
import { ElMessage, ElTable } from "element-plus";
import { ref } from "vue";
import { useRoute } from "vue-router";
import { createOrderService } from "@/api/orders";
import { useUserInfoStore } from "@/stores/userInfo";
import { deleteCartService } from "@/api/cart";
import { debounce } from "lodash";
import { ArrowDown } from "@element-plus/icons-vue";

const route = useRoute();
const userInfoStore = useUserInfoStore();

// 订单商品数据
const orderCommodity = ref(JSON.parse(route.query.commodityConfirm));

console.log(orderCommodity.value);

// 订单商品数量变化
const orderQuantityChange = (data) => {
    // 删除旧数据
    totalAmount.value -= data.totalPrice;
    if (data.quantity <= 1) {
        ElMessage.error("商品数量不能小于1");
        data.quantity = 1;
    } else {
        data.totalPrice = data.quantity * data.sku.price;
    }
    // 添加新数值
    totalAmount.value += data.totalPrice;
};

// 订单删除商品
const orderDelete = async (data) => {
    totalAmount.value -= data.totalPrice;
    const index = orderCommodity.value.findIndex((item) => item === data);
    if (index !== -1) {
        orderCommodity.value.splice(index, 1);
    }
    // 清空data数据
    console.log(data);
};

// 订单总计金额
const totalAmount = ref(
    orderCommodity.value.reduce((acc, cur) => acc + cur.totalPrice, 0)
);
// 选择的地址
let selectedAddress = ref(userInfoStore.address[0]);
// 结算
const settleAccounts = debounce(async () => {
    if (orderCommodity.value.length === 0) {
        return ElMessage.error("订单商品为空，请重新选择商品");
    }
    // 调用支付接口
    let orderDetails = orderCommodity.value.map((item) => {
        return {
            commodityId: item.commodity.commodityId,
            skuId: item.sku.skuId,
            quantity: item.quantity,
            totalPrice: item.totalPrice,
            addressId: selectedAddress.value.addressId,
            receiverName: selectedAddress.value.addressName,
            receiverPhone: selectedAddress.value.addressPhone,
            receiverAddressDescription: selectedAddress.value.addressDescription,
        };
    });
    // 创建订单
    let res = await createOrderService(orderDetails);
    console.log(res);
    if (res.code === 1) {
        ElMessage.error(res.message);
        return;
    }

    // 删除购物车的商品
    if (orderCommodity.value[0].cartId !== undefined) {
        let cartIds = orderCommodity.value.map((item) => item.cartId);
        await deleteCartService(cartIds);
    }
    // 跳转支付界面
    ElMessage.info("跳转支付界面中...");

    // // 支付接口
    window.open(
        "http://127.0.0.1:8081/alipay/pay?subject=" +
            orderCommodity.value[0].commodity.commodityTitle.substr(0, 8) +
            "..." +
            "&traceNo=" +
            res.data +
            "&totalAmount=" +
            totalAmount.value +
            "&userId=" +
            userInfoStore.info.userId,
        "_self"
    );
}, 500);

// 地址弹出状态
const addressDialogVisible = ref(false);
// 地址选择状态
const addressSelectedStatus = (val) => {
    if (val.selected == true) {
        val.selected = false;
        return;
    }
    // 将所有地址的selected属性设置为false
    userInfoStore.address.forEach((element) => {
        element.selected = false;
    });
    // 将选中的地址的selected属性设置为true
    val.selected = true;
    // 保存选中的地址id
    selectedAddress.value = val;
    console.log(selectedAddress);
};
</script>


<template>
    <el-container class="container">
        <el-header>
            <el-row>
                <!-- 标题 -->
                <el-col class="recommend-commodity-title" :span="24">
                    <text>订单确认</text>
                </el-col>
            </el-row>
        </el-header>
        <el-container>
            <el-main>
                <el-row gutter="20">
                    <!-- 订单列表 -->
                    <el-col :span="18">
                        <el-table
                            class="table-container"
                            max-height="700"
                            :data="orderCommodity"
                        >
                            <el-table-column
                                width="200"
                                align="center"
                                label="商品"
                            >
                                <template #default="scope">
                                    <router-link
                                        :to="`/commodity/detail/${scope.row.commodity.commodityId}`"
                                    >
                                        <img
                                            class="commodity-img"
                                            :src="
                                                scope.row.commodity.coverImage
                                            "
                                            alt=""
                                        />
                                    </router-link>
                                </template>
                            </el-table-column>
                            <el-table-column
                                align="center"
                                class="commodity-title"
                                prop="commodity.commodityTitle"
                                label="标题"
                            >
                            </el-table-column>
                            <el-table-column width="200" label="规格">
                                <template #default="scope">
                                    <span
                                        v-for="(item, index) in scope.row.sku
                                            .specs"
                                        :key="index"
                                        >{{ item.name }}: {{ item.valueName
                                        }}<br
                                    /></span>
                                </template>
                            </el-table-column>
                            <el-table-column
                                width="200"
                                align="center"
                                label="数量"
                            >
                                <template #default="scope">
                                    <!-- v-model报错[Vue warn]: 
                             Invalid prop: type check failed for prop "modelValue". 
                             Expected Number with value 5, got String with value "5".
                             解决方法：将v-model绑定的值类型转换为Number类型，如：:v-model="scope.row.cartQuantity - 0"
                               -->
                                    <el-input-number
                                        @change="orderQuantityChange(scope.row)"
                                        v-model="scope.row.quantity"
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column width="100" label="价格">
                                <template #default="scope">
                                    <text class="cart-price"
                                        >{{ scope.row.totalPrice }}￥</text
                                    >
                                </template>
                            </el-table-column>
                            <el-table-column
                                width="100"
                                align="center"
                                label="操作"
                            >
                                <template #default="scope">
                                    <el-button
                                        type="danger"
                                        @click="orderDelete(scope.row)"
                                    >
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                    <el-col :span="6">
                        <div class="main-right">
                            <div class="account-title">收货地址</div>
                            <el-divider />
                            <div
                                class="address-selected"
                                @click="addressDialogVisible = true"
                            >
                                <tbody>
                                    <tr>
                                        <td>
                                            {{ selectedAddress.addressName }}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            {{ selectedAddress.addressPhone }}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            {{
                                                selectedAddress.addressDescription
                                            }}
                                        </td>
                                    </tr>
                                </tbody>
                            </div>
                            <el-divider />
                            <!-- 地址列表 -->
                            <div class="account-total">
                                <tbody>
                                    <tr>
                                        <td>合计：</td>
                                        <td class="total-price">
                                            {{ totalAmount }}
                                        </td>
                                    </tr>
                                </tbody>
                            </div>
                            <!-- 结算按钮 -->
                            <el-button
                                class="account-btn"
                                type="primary"
                                @click="settleAccounts"
                                >结算</el-button
                            >
                        </div>
                    </el-col>
                </el-row>
            </el-main>
        </el-container>
    </el-container>

    <!-- 地址弹出框 -->
    <el-dialog
        style="
            max-height: 500px;
            max-width: 1000px;
            overflow-y: auto;
            overflow-x: hidden;
        "
        v-model="addressDialogVisible"
        title="更改收货地址"
        align-center
    >
        <div v-for="(item, index) in userInfoStore.address" :key="index">
            <el-button
                class="address-dialog-btn"
                :class="{
                    selected: item.selected,
                }"
                @click="
                    addressSelectedStatus(item), (addressDialogVisible = false)
                "
            >
                <tbody>
                    <tr>
                        <td>收货人：</td>
                        <td>{{ item.addressName }}</td>
                    </tr>
                    <tr>
                        <td>手机号：</td>
                        <td>{{ item.addressPhone }}</td>
                    </tr>
                    <tr>
                        <td>收货地址：</td>
                        <td>{{ item.addressDescription }}</td>
                    </tr>
                </tbody>
            </el-button>
        </div>
    </el-dialog>
</template>



<style scoped lang = "scss">
@import "@/assets/style/config.scss";

@mixin sku-state-mixin {
    &.selected {
        border: 1px solid;
        border-color: $themeColor;
        background-color: $themeColor;
        color: white;
    }

    &.disabled {
        opacity: 0.6;
        border-style: dashed;
        cursor: not-allowed;
    }
}

// 结算框中的公共样式
$fontSize: 18px;
$priceColor: rgb(190, 36, 36);

.container {
    width: 100%;
}
.commodity-img {
    width: 100px;
    border-radius: 15px;
}

.recommend-commodity-title {
    text-align: center;
    font-size: 30px;
}

.table-container {
    font-size: 16px;
    width: auto;
}
.cart-price {
    color: $priceColor;
    font-size: 15px;
}
.footer {
    width: 80%;
    margin: 0 auto;
}

.account-title {
    font-size: $fontSize;
}
.account-total {
    // 设置合计的边距
    margin: 20px 0;
    font-size: $fontSize;
}
.total-price {
    color: $priceColor;
    font-size: $fontSize;
}
.account-btn {
    width: 100%;
    height: 50px;
    font-size: 18px;
    background-color: #eb7c44;
    border: none;
}
.address-dialog-btn {
    width: auto;
    height: auto;
    text-align: left;
    font-size: 16px;
    margin: 5px;
    @include sku-state-mixin;
}
.main-right {
    height: auto;
    background-color: #f3f6f8;
    border-radius: 10px;
    padding: 20px;
    text-align: left;
    font-size: 16px;
    margin-bottom: 20px;
    padding: 15px;
}
.address-selected:hover {
    border: 1px solid $themeColor;
    border-radius: 15px;
}
</style>